package com.YxyBackMange.Service.Sys.Impl;

import com.YxyBackMange.Entity.Sys.SysReUserRole;
import com.YxyBackMange.Entity.Sys.SysRole;
import com.YxyBackMange.Entity.Sys.SysUser;
import com.YxyBackMange.Mapper.Sys.SysReUserRoleMapper;
import com.YxyBackMange.Mapper.Sys.SysRoleMapper;
import com.YxyBackMange.Mapper.Sys.SysUserMapper;
import com.YxyBackMange.Service.Sys.SysUserService;
import com.YxyBackMange.Util.MD5;
import com.YxyBackMange.Util.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysReUserRoleMapper sysReUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public SysUser insertService(SysUser o) {
        if(o.getRoleIdArray()==null||o.getRoleIdArray().length<1)
        {
            return null;
        }
        String password= MD5.createMD5(o.getToken());
        String salt= MyUtil.getRandomCharAndNumr(10);
        o.setRegisterTime(new Date());
        o.setSalt(salt);
        o.setToken(MD5.createMD5(password+salt));
        sysUserMapper.insertSelective(o);
        for (Integer roleId:o.getRoleIdArray())
        {
            SysReUserRole sysReUserRole=new SysReUserRole();
            sysReUserRole.setUserId(o.getId());
            sysReUserRole.setRoleId(roleId);
            sysReUserRoleMapper.insertSelective(sysReUserRole);
        }
        return o;
    }
    @Override
    public SysUser updateService(SysUser o) {
        if(o.getRoleIdArray()==null||o.getRoleIdArray().length<1)
        {
            return null;
        }
        sysUserMapper.updateByPrimaryKeySelective(o);
        SysReUserRole sysReUserRole=new SysReUserRole();
        sysReUserRole.setUserId(o.getId());
        sysReUserRoleMapper.delete(sysReUserRole);
        for (Integer roleId:o.getRoleIdArray())
        {
            sysReUserRole=new SysReUserRole();
            sysReUserRole.setUserId(o.getId());
            sysReUserRole.setRoleId(roleId);
            sysReUserRoleMapper.insertSelective(sysReUserRole);
        }
        return o;
    }

    @Override
    public SysUser insert(SysUser o) {
        sysUserMapper.insertSelective(o);
        return o;
    }

    @Override
    public SysUser update(SysUser o) {
        sysUserMapper.updateByPrimaryKeySelective(o);
        return o;
    }

    @Override
    public SysUser delete(SysUser o) {
        sysUserMapper.delete(o);
        return o;
    }
}
